package be.kuleuven.mume.query;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;

import be.kuleuven.mume.PMF;
import be.kuleuven.mume.beans.PersoonBean;
import be.kuleuven.mume.beans.VakBean;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class VakQuery {
	
	//private static Logger log = Logger.getLogger(VakQuery.class.getName());
	
	public static VakBean getVak(String vakId) {
		PersistenceManager pm = PMF.getPersistenceManager();
		Key key = KeyFactory.stringToKey(vakId);
		VakBean result = pm.getObjectById(VakBean.class, key);
		pm.close();
		return result;
	}
	
	public static List<PersoonBean> getVakStudenten(final String vakId, final int page, final int rpp) {
		QueryHelper<List<PersoonBean>> h = new QueryHelper<List<PersoonBean>>() {
			
			@Override
			protected List<PersoonBean> execute(PersistenceManager pm) {
				Key vakKey = KeyFactory.stringToKey(vakId);
				VakBean vak = pm.getObjectById(VakBean.class, vakKey);
				List<PersoonBean> result = new ArrayList<PersoonBean>();
				List<String> studenten = vak.getStudenten();
				for (int i = (page*rpp) ; i < Math.min(((page+1) * rpp), studenten.size()) ; i++) {
					String pers = studenten.get(i);
					Key persK = KeyFactory.stringToKey(pers);
					result.add(pm.getObjectById(PersoonBean.class, persK));
				}
				return result;
			}
		};
		return h.executeQuery();
	}
	
	public static boolean addStudent(final String vakId, final String persoonId) {
		if(!PersoonQuery.checkPersoon(persoonId, true))
			return false;
		
		UpdateQueryHelper<VakBean> h = new UpdateQueryHelper<VakBean>(vakId){
			@Override
			public Boolean doUpdate(VakBean objectToUpdate) {
				return objectToUpdate.addStudent(persoonId);
			}
			
		};
		return h.executeQuery();
	}
	
	public static boolean removeStudent(final String vakId, final String persoonId) {
		if(!PersoonQuery.checkPersoon(persoonId, true))
			return false;
		
		UpdateQueryHelper<VakBean> h = new UpdateQueryHelper<VakBean>(vakId){
			@Override
			public Boolean doUpdate(VakBean objectToUpdate) {
				return objectToUpdate.removeStudent(persoonId);
			}
			
		};
		return h.executeAtomicQuery();
	}
}
